package com.xinghanlaser.applet.points;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinghanlaser.applet.base.common.exception.ServiceException;
import com.xinghanlaser.applet.base.flow.core.BasePoint;
import com.xinghanlaser.applet.entity.TopicHandleDetail;
import com.xinghanlaser.applet.service.ITopicHandleDetailService;
import com.xinghanlaser.applet.service.ITopicHandleHistoryService;
import com.xinghanlaser.applet.service.ITopicService;
import com.xinghanlaser.applet.vo.point.DoorHandleVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/14 15:28
 */
@Component
public class DoorHandlePoint extends BasePoint<DoorHandleVO> {
    @Resource
    private ITopicService topicService;

    @Resource
    private ITopicHandleDetailService handleService;

    @Resource
    private ITopicHandleHistoryService historyService;

    @Override
    @DSTransactional
    protected void pointOperation(DoorHandleVO vo) {
        // 校验申请单是否存在
        final Long topicId = vo.getTopicId();
        final String handler = vo.getHandler();
        final String handlerPhone = vo.getHandlerPhone();
        final String reachTime = vo.getReachTime();
        topicService.validatedTopicId(topicId);

        // 更新处理流程信息
        TopicHandleDetail handleEntity = topicService.getHandleEntityByTopicId(topicId);
        handleEntity.setHandler(handler)
                .setHandlerPhone(handlerPhone)
                .setCurrentPointId(getPointId());
        handleService.updateById(handleEntity);

        // 保存处理流程历史信息
        Map<String , String > handlerDescMap = new HashMap<>();
        handlerDescMap.put("handler", handler);
        handlerDescMap.put("handlerPhone", handlerPhone);
        handlerDescMap.put("reachTime", reachTime);
        if (StrUtil.isNotBlank( vo.getHandleNote())) {
            handlerDescMap.put("handleNote", vo.getHandleNote());
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(handlerDescMap);

            historyService.saveHistory(
                    handleEntity.getId(),
                    getPointId(),
                    "已派遣人员上门处理",
                    jsonString
            );

        } catch (IOException e) {
            throw new ServiceException("转化json服务异常");
        }
    }

    @Override
    protected Class<DoorHandleVO> getPointDataType() {
        return DoorHandleVO.class;
    }

    @Override
    public Long getPointId() {
        return 5L;
    }
}
